package com.hou.mytomcat.myClassLoader;

import org.apache.tools.ant.taskdefs.optional.Javah;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 加载myTomcat的类加载器
 */
// TODO: 为什么放到包下面，全限定名找不到这个类
public class CommonClassLoader extends URLClassLoader {
    private ClassLoader parent;
    public CommonClassLoader(ClassLoader parent) {
        super(new URL[] {});
        this.parent = parent;
        try {
            File workingFolder = new File("d:/web/mytomcat/");
            //公共类加载器，加载lib目录下的所有jar包
            File libFolder = new File(workingFolder, "lib");
            File[] jarFiles = libFolder.listFiles();
            for(File file : jarFiles) {
                if(file.getName().endsWith("jar")) {
                    URL url = new URL("file:" + file.getAbsolutePath());
                    this.addURL(url);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

//    @Override
//    protected Class<?> loadClass(String name, boolean resolve)
//            throws ClassNotFoundException
//    {
//        synchronized (getClassLoadingLock(name)) {
//            // First, check if the class has already been loaded
//            Class<?> c = findLoadedClass(name);
//
//            if (c == null) {
//                // If still not found, then invoke findClass in order
//                // to find the class.
//                long t1 = System.nanoTime();
//                if(name.startsWith("com.hou"))
//                    c = findClass(name);
//                else {
//                    c = this.getParent().loadClass(name);
//                }
//                // this is the defining class loader; record the stats
////                sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
//                sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
//                sun.misc.PerfCounter.getFindClasses().increment();
//            }
//
//            if (resolve) {
//                resolveClass(c);
//            }
//            return c;
//        }
//    }
}
